package cn.slipi.pan.common.filter;

import cn.slipi.pan.common.constants.ExceptionConstants;
import cn.slipi.pan.common.exception.ServiceException;
import cn.slipi.pan.common.response.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * 全局异常过滤器
 */
@Slf4j
@Component
public class GlobalExceptionFilter implements Filter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (Throwable e) {
            log.error("global error", e);

            if (e instanceof ServiceException serviceException) {
                ctx.render(
                        new ApiResult<>()
                                .setCode(serviceException.getCode())
                                .setMessage(serviceException.getMessage())
                );
                return;
            }

            ctx.render(
                    new ApiResult<>()
                            .setCode(ExceptionConstants.SYSTEM_ERROR.getCode())
                            .setMessage(ExceptionConstants.SYSTEM_ERROR.getMessage())
                            .setError(ExceptionUtils.getStackTrace(e))
            );
        }
    }
}
